import router from "./router";
import { getToken } from "@/utils/auth";
import { useUserStore } from "@/stores/user";
import {usePermissionStore} from "@/stores/permission";

const whiteList = ["/login", "/auth-redirect", "/bind", "/register"];
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const permission = usePermissionStore();
  if (getToken()) {
    if (userStore.roles.length == 0) {
      userStore
        .getInfo()
        .then(() => {
          permission.GenerateRoutes().then()
          next();
        })
        .catch((err) => {
          console.error(err);
          userStore.logout().then(() => {
            next({ path: "/" });
          });
        });
    } else {
      next();
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
    }
  }
});
